package models.mappers;

import java.util.List;

import models.BuyerAccount;

import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import vos.BuyerAccountSearchVo;
import enums.Platform;

public interface BuyerAccountMapper {
	
	int count(BuyerAccountSearchVo vo);
	
	List<BuyerAccount> selectBySearch(BuyerAccountSearchVo vo);

	@Insert("insert into buyer_account" +
			"(nick,gender,platform,consignee,state,city,region,address,mobile,user_id,status,create_time,modify_time,pic_url,level,age) " +
			"values(#{nick},#{gender},#{platform},#{consignee},#{state},#{city},#{region},#{address},#{mobile},#{userId},#{status},#{createTime},#{modifyTime},#{picUrl}, #{level}, #{age})")
	void insert(BuyerAccount account);
	
	void updateById(BuyerAccount account);
	
	BuyerAccount selectById(Long id);

    BuyerAccount selectForCheckDuplicate(BuyerAccount svo);
    
    @Select("select id,nick,gender,state,city,region,address,consignee,mobile,status,memo,order_number from " + BuyerAccount.TABLE_NAME 
        +" where user_id=#{userId} and platform=#{platform}")
    List<BuyerAccount> selectByUserIdAndPlatform(@Param("userId") long userId, @Param("platform")  Platform platform);

    void updateBuyerAccount(BuyerAccount vo);

	@Select("select * from " + BuyerAccount.TABLE_NAME + " where id = #{accountId}")
	BuyerAccount findCountByAccountId(@Param("accountId") long accountId);

	@Update("update " + BuyerAccount.TABLE_NAME + " set order_number = #{orderNumber} where id=#{id}")
	void updateOrderNumber(@Param("id")long id, @Param("orderNumber")long orderNumber);
	
	@Select("SELECT * FROM buyer_account ba "+
			"WHERE ba.user_id = #{buyerId} and ba.status='EXAMINED' "+
			"AND EXISTS ( SELECT 1 FROM task t WHERE t.id = #{taskId} AND ( t.platform = ba.platform OR ( ba.platform = 'TAOBAO' AND ( t.platform = 'TAOBAO' OR t.platform = 'TMALL')))) "+
			"AND NOT EXISTS ( SELECT 1 FROM buyer_task bt WHERE bt.buyer_account_id = ba.id AND bt.task_id = #{taskId} and bt.status!='CANCLED') ")
	List<BuyerAccount> selectAvailableAccountByTaskId(@Param("taskId") Long taskId, @Param("buyerId")Long buyerId);
		
	@Select("select count(1) from " + BuyerAccount.TABLE_NAME + " where platform= #{platform} and user_id = #{userId}")
	int countByPlatform(@Param("platform")  Platform platform, @Param("userId") Long userId);
	
}
